package com.zxjbyte.yiyi.framework.web.filter;

import cn.hutool.core.lang.Singleton;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.zxjbyte.yiyi.framework.web.config.XssProperties;
import com.zxjbyte.yiyi.framework.web.xss.wrapper.YiyiXssHttpServletRequestWrapper;
import com.zxjbyte.yiyi.framework.web.xss.clean.IXssCleaner;
import lombok.RequiredArgsConstructor;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author zhangxingjia
 * @Date 2023/3/17 20:24
 * @Version: 1.0
 */
@RequiredArgsConstructor
public class YiyiRequestFilter extends OncePerRequestFilter {

    private final XssProperties xssProperties;
    private final IXssCleaner xssCleaner;
    private final PathMatcher antPathMatcher = Singleton.get(AntPathMatcher.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if(!xssProperties.getEnabled() || isXssSkip(request.getRequestURI())){
            filterChain.doFilter(new YiyiHttpServletRequestWrapper(request), response);
        } else {
            filterChain.doFilter(new YiyiXssHttpServletRequestWrapper(request, xssCleaner), response);
        }

    }

    private boolean isXssSkip(String path) {
        String contextPath = SpringUtil.getProperty("server.servlet.context-path");
        return (StrUtil.isNotBlank(contextPath) && !StrUtil.startWithIgnoreCase(path, contextPath))
                || xssProperties.getSkipPath().stream().anyMatch(pattern -> antPathMatcher.match(pattern, path));
    }


}
